import {
  addCart,
  getCart,
  updateCart,
  deleteCart
} from '../../api/cartApi.js'

import router from '../../router/index.js'

export default {
  namespaced: true,
  state: {
    //购物车数据
    cart_list: [],
    //总价
    total: 0,
    //全选状态
    all_checked: false
  },
  getters: {},
  mutations: {
    set_cart_list(state, value) {
      state.cart_list = value;
      //计算总价
      let sum = 0;
      let flag = true;
      state.cart_list.forEach(function(cart) {
        if (cart.cart_checked == 1) {
          sum += cart.cart_count * cart.cart_price
        } else {
          flag = false
        }
      });
      state.total = sum;
      state.all_checked = flag;
    }
  },
  actions: {
    //添加购物车
    add_cart(context) {
      addCart({
        cart_spuid: context.rootState.product.spu.spu_id,
        cart_name: context.rootState.product.sku.sku_name,
        cart_skuid: context.rootState.product.sku.sku_id,
        cart_sku: JSON.stringify(context.rootState.product.sku_attr_list),
        cart_thumburl: context.rootState.product.spu.attrKeyList[0].attrValueList[context.rootState.product
          .ablum_index].value_images[context.rootState.product.ablum_item_index],
        cart_price: context.rootState.product.sku.sku_price,
        cart_count: context.rootState.product.buy_number,
      }).then(function(response) {
        if (response.data.httpcode == 200) {
          router.push({
            path: '/cart'
          })
        } else {
          router.push({
            path: '/login'
          })
        }
      })
    },
    // 查询购物车
    get_cart_list(context) {
      getCart({}).then(function(response) {
        console.log(response.data.data)
        context.commit('set_cart_list', response.data.data);
      })
    },
    //修改购物车
    update_cart(context, value) {
      updateCart(value).then(function(response) {
        if (response.data.httpcode == 200) {
          context.dispatch('get_cart_list');
        }
      })
    },
    //删除购物车
    delete_cart(context, value) {
      // console.log(value.car_id)
      deleteCart(value.car_id).then(function(response) {
        if (response.data.httpcode == 200) {
          context.dispatch('get_cart_list');
        }
      })
    }
  }
}
